package com.liwei.lwmail.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.liwei.common.utils.HttpUtils;
import com.liwei.common.utils.R;
import com.liwei.lwmail.auth.feign.MemberFeignService;
import com.liwei.common.vo.MemberResponseVo;
import com.liwei.lwmail.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String,String> header = new HashMap<>();
        Map<String,String> query = new HashMap<>();
        //1、根据code换取accessToken
        Map<String,String> map = new HashMap<>();
        map.put("client_id","471475267");
        map.put("client_secret","65274149b2cb4d0dc22cc347a9698b12");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.lwmall.com/oauth2.0/weibo/success");
        map.put("code",code);

        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", header, query, map);

        //2、处理
        if (response.getStatusLine().getStatusCode() == 200){
            //获取到了token
            String jsonStr = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(jsonStr, SocialUser.class);

            //判断用户是否第一次进入，决定登录还是注册
            //如果用户第一次进入网站，自动注册：与会员表绑定(为当前用户生成一个会员信息账号)
            R r = memberFeignService.oauthLogin(socialUser);
            if (r.getCode() == 0){
                MemberResponseVo memberResponseVo = r.getData("data", new TypeReference<MemberResponseVo>() {});
                session.setAttribute("loginUser",memberResponseVo);
                //3、成功跳回首页
                return  "redirect:http://lwmall.com";
            }else {
                return  "redirect:http://auth.lwmall.com/login.html";
            }

        }else {
            return  "redirect:http://auth.lwmall.com/login.html";
        }
    }
}
